# class  Tree:
#     def __init__(self):
#         self.left = None
#         self.right = None
#         self.data = None
#
#
# root = Tree()
#
# root.data = '中国'
#
# root.left = Tree()

#
# root.left.data = '山西'
#
# root.right = Tree()
# root.right.data = '北京'
#
# root.left.left = Tree()
#
# root.left.left.data = '吕梁'
#
# print(root.data)
import json
import os
import time

import httpx
import jwt
import redis
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.models import *
from myapp.models import User
from myapp.ser import HLSocketSer


class BSTnode:
    def __init__(self,val):
        self.val = val
        self.left = None
        self.right = None
        self.parent = None

class BST:

    def __init__(self):
        self.root = None
    def insert(self,val):
        newNode = BSTnode(val)
        if self.root is None:
            self.root = newNode
        else:
            curNode = self.root
            while True:
                if val < curNode.val:
                    if curNode.left is None:
                        curNode.left = newNode
                        newNode.parent = curNode
                        break
                    curNode = curNode.left
                else:
                    if curNode.right is None:
                        curNode.right = None
                        newNode.parent = curNode
                        break
                    curNode = curNode.right
    def find(self,val):
        curNode = self.root
        while curNode is not None:
            if val < curNode.val:
                curNode = curNode.left
            elif val > curNode.val:
                curNode = curNode.right
            else:
                return  True
            return False

mylist = [2,6,7,4,8,8,9]
bst = BST()
for x in range(len(mylist)):
    bst.insert(mylist[x])
print(bst.find(0))


# class meta:


class RegisterView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        name = request.data.get('name')
        identity = request.data.get('identity')
        home = request.data.get('home')
        User.objects.create(username=username,password=password,name=name,identity=identity,home=home)
        return Response({'msg': '注册成功', 'code': 200})

#获取客户端ip

from dwebsocket.decorators import accept_websocket
r = redis.Redis(host='localhost')




@accept_websocket
def test_websocket(request):
    while True:
        if request.is_websocket():
            time.sleep(0.5)

        request.websocket.send(json.dumps({'count': r.scard('set_ip')}))




class GetOnLines(APIView):
    def get(self, request):

        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            ip = request.META.get('REMOTE_ADDR')

        if r.scard('set_ip'):
            r.sadd('set_ip', ip)
        else:
            r.sadd('set_ip', ip)
            r.expire('set_ip', 10)

        return Response({'online': r.scard('set_ip')})





def Loglens(request):
    r = redis.Redis(decode_responses=True)
    if r.exists('loginset'):
        r.sadd('loginset', request.META['REMOTE_ADDR'])

    else:
        r.expire('loginset', 300)
        r.sadd('loginset', request.META['REMOTE_ADDR'])

    return JsonResponse({'msg': r.scard('loginset')})


@accept_websocket
def websocket(request):
    if request.is_websocket():
        r = redis.Redis(decode_responses=True)
        while True:
            if r.exists('loginset'):
                r.sadd('loginset', request.META['REMOTE_ADDR'])

            else:
                r.expireat('loginset', 300)
                r.sadd('loginset', request.META['REMOTE_ADDR'])

            request.websocket.send(json.dumps(r.scard('loginset')))
from myapp.ser import *

class HLView(APIView):
    def get(self, request):
        data = HLSer(HLModel.objects.all())  # 从数据库中读取数据

        # 获取数据后判断数据是否更新
        y = datetime.datetime.strptime(data[0]['update'], '%Y-%m-%d')
        z = str(datetime.datetime.now()).split(' ')[0]
        z = datetime.datetime.strptime(z, '%Y-%m-%d')
        if (z - datetime.timedelta(days=1)) == y:
            # 判断到数据未更新，更新数据，返回库中数据
            url = 'http://op.juhe.cn/onebox/exchange/query?key=' + AppId
            data = eval(httpx.get(url).text)
            HLModel.objects.create(update=str(data['result']['update']), json=str(data['result']['list']))

        date = []
        huilv = []

        for i in data:
            date.append(i['update'])
            huilv.append(i['json'][0][2])

        return Response({'date': date, 'huilv': huilv})
import datetime
@accept_websocket
def HLsocket(request):
    # 获取当前日期
    t = datetime.date.today()
    print(t)
    # 获取当天的数据
    res = HLSocketSer(HLSocket.objects.filter(date=str(t)))
    # 发送数据
    js = {
        'json': [i['json'] for i in res],
        'time': [i['time'] for i in res],
        'date': [i['date'] for i in res],
    }
    request.websocket.send(json.dumps({'data': js, 'res': 0}))
    # 卡住程序，等待下一分钟到来
    time.sleep(30)
    while True:
        # 开始无限循环推送
        url = 'http://op.juhe.cn/onebox/exchange/query?key=' + AppId
        # 请求数据
        data = eval(httpx.get(url).text)
        # 进行入库操作
        times = data['result']['update']
        times = times.split(' ')
        HLSocket.objects.create(
            date=times[0],
            time=times[1],
            json=data['result']['list'][0][2]
        )
        # 提取数据
        js = {
            'date': times[0],
            'time': times[1],
            'json': data['result']['list'][0][2]
        }
        # 推送到前端
        request.websocket.send(json.dumps({'data': js, 'res': 1}))
        # 休眠，等待一分钟后再次推送
        time.sleep(60)

class OrderView(APIView):
    def get(self, request):
        token = request.GET.get('token')
        uid = jwt.decode(token, '123')['uid']
        print(uid)
        query_lis = []
        query_lis.append(Orderone.objects.filter(uid=uid))
        query_lis.append(Ordertow.objects.filter(uid=uid))
        data = OrderSer(query_lis)
        return Response({'data': data})

class OrderItem(APIView):
    def get(self,request):
        order_id = request.GET.get('order_id')
        query_lis = []
        query_lis.append(Orderone.objects.filter(order_id=order_id))
        query_lis.append(Ordertow.objects.filter(order_id=order_id))
        data = OrderSer(query_lis)
        return Response({'data': data})



































